package com.iris.live.services.services.impl;

import com.iris.live.services.common.DateFormatUtils;
import com.iris.live.services.data.models.临时接待记录Model;
import com.iris.live.services.data.models.销售顾问状态Model;
import com.iris.live.services.data.models.销售顾问状态ModelPK;
import com.iris.live.services.data.models.顾客进店记录表Model;
import com.iris.live.services.data.repositories.ForeGroundRepository;
import com.iris.live.services.data.repositories.临时接待记录Repository;
import com.iris.live.services.data.repositories.销售顾问状态Repository;
import com.iris.live.services.data.repositories.顾客进店记录表Repository;
import com.iris.live.services.models.ResultData;
import com.iris.live.services.services.ForeGroundService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.sql.Time;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ForeGroundServiceImpl implements ForeGroundService {
    private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ForeGroundServiceImpl.class);

    @Autowired
    private ForeGroundRepository foreGroundRepository;

    @Autowired
    private 临时接待记录Repository teampRecepRepository;

    @Autowired
    private 顾客进店记录表Repository custEnterStoreRecordRepository;

    @Autowired
    private 销售顾问状态Repository saleStatusRepository;

    @Override
    public List getUnfinishTRRecord(GetTemporaryReceptionRecordRequest request) {
        return foreGroundRepository.getUnfinishTRRecord(request.permit, request.salesConsultant, request.date);
    }

    @Override
    public List getReceptionTimeAndNumberByRNum(Integer teampReceptionNum) {
        return foreGroundRepository.getReceptionTimeAndNumberByRNum(teampReceptionNum);
    }
    static   DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    static DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");

    //11.16 xxd 下午
    @Override
    @Transactional
    public boolean updTeampRecepInfoAndCustInStoreInfo(Integer teampReceptionNum, String xuke, String zhanghao) {
        boolean flag;
        try {
//            Date date = new Date(System.currentTimeMillis());
//            DateFormat dateFormat = new SimpleDateFormat("HH:mm:SS");
//            String prase = dateFormat.format(date);
//            Date finalDate = dateFormat.parse(prase);
//
//            java.sql.Time time = new java.sql.Time(finalDate.getTime());

            临时接待记录Model lianshimodel = teampRecepRepository.getModelByTeampNums(teampReceptionNum);
            if (lianshimodel.get进店编号() != null && !lianshimodel.get进店编号().equals("")) {
                int niamde = lianshimodel.get临时接待编号();
                //teampRecepRepository.updTeampRecetInfo(finalDate, niamde);
                临时接待记录Model nimademodel = teampRecepRepository.findOne(niamde);
                Date ssd = new Date();
                nimademodel.set结束接待时间(new Time(ssd.getTime()));
                nimademodel.set是否接待完成("是");
                nimademodel.set更新账号(zhanghao);
                teampRecepRepository.save(nimademodel);

                //临时接待记录Model modelByTeampNum = teampRecepRepository.getModelByTeampNum(niamde);
                顾客进店记录表Model nidmddddd = custEnterStoreRecordRepository.findOne(lianshimodel.get进店编号());
                nidmddddd.set离店时间(Time.valueOf(LocalTime.now()));
                // u.停留时间='4',u.操作人='Admin@lsh.com',u.更新账号='Admin@lsh.com'

                // nidmddddd.set停留时间(4);
                //11.29 外包bug
               /* LocalTime starLocal = lianshimodel.get开始接待时间().toLocalTime();
                LocalTime timenow = LocalTime.now();
                int starhour = starLocal.getHour();
                int endhousr = timenow.getHour();
                int starhours = starLocal.getMinute();
                int endhousrs = timenow.getMinute();
                int fenzhogn = endhousrs - starhours;
                int hours = endhousr - starhour;
                if (hours > 0) {
                    if (fenzhogn > 0) {
                        nidmddddd.set停留时间(fenzhogn + hours * 60);
                    } else {
                        nidmddddd.set停留时间(fenzhogn + hours * 60);
                    }
                } else {
                    nidmddddd.set停留时间(fenzhogn);
                }*/
                /**
                 *
                 * 计算两个日期小时和分钟之差. (分钟)
                 *
                 */
                Date nowDateTime=new Date();
                String sDate=dateFormat.format(lianshimodel.get接待日期());
                String sTime=timeFormat.format(lianshimodel.get开始接待时间());
                String sDateTime=sDate+" "+sTime;
                String nowDateTimeStr= simpleDateFormat.format(nowDateTime);

                int s= getDistanceTimes(sDateTime,nowDateTimeStr);
                nidmddddd.set停留时间( s);
                //-----------------------------

                nidmddddd.set离店时间(new Time(ssd.getTime()));
                nidmddddd.set操作人(zhanghao);
                nidmddddd.set更新账号(zhanghao);
                custEnterStoreRecordRepository.save(nidmddddd);
                // custEnterStoreRecordRepository.updLeavfTimeByEnterStoreNum(finalDate, );


            } else {
                // 为null 则插入 顾客进店记录表+  同时 把  进店编号  更新+更新账号
                顾客进店记录表Model newmodel = new 顾客进店记录表Model();
                java.sql.Timestamp ts = new java.sql.Timestamp(System.currentTimeMillis());
                newmodel.set更新时间(ts);
                newmodel.set许可(xuke);
                newmodel.set更新账号(zhanghao);

                newmodel.set销售顾问(lianshimodel.get销售顾问());
                newmodel.set是否来电("否");
                newmodel.set是否留档("否");
                newmodel.set是否新留档("否");
                //维持ilog原有逻辑，未留档客户，首次到店=是
                newmodel.set是否首次到店("是");
                newmodel.set是否预约("否");
                newmodel.set是否指定销售顾问(null);

                newmodel.set是否评估("否");
                newmodel.set是否置换("否");
                newmodel.set是否试驾("否");
                newmodel.set是否报价("否");
                newmodel.set是否金融("否");
                newmodel.set是否订单("否");
                newmodel.set是否零售("否");
                newmodel.set是否交车("否");

                newmodel.set进店日期(lianshimodel.get接待日期());
                Date dd = new Date();
                newmodel.set离店时间(new Time(dd.getTime()));

                newmodel.set到店时间(lianshimodel.get开始接待时间());
             /*   LocalTime starLocal = lianshimodel.get开始接待时间().toLocalTime();
                LocalTime timenow = LocalTime.now();

                int starhour = starLocal.getHour();
                int endhousr = timenow.getHour();

                int starhours = starLocal.getMinute();
                int endhousrs = timenow.getMinute();

                int fenzhogn = endhousrs - starhours;

                int hours = endhousr - starhour;
                if (hours > 0) {
                    if (fenzhogn > 0) {
                        newmodel.set停留时间(fenzhogn + hours * 60);
                    } else {
                        newmodel.set停留时间(fenzhogn + hours * 60);
                    }
                } else {
                    newmodel.set停留时间(fenzhogn);

                }*/

                /**
                 *
                 * 计算两个日期小时和分钟之差. (分钟)
                 *
                 */
                Date nowDateTime=new Date();
                String sDate=dateFormat.format(lianshimodel.get接待日期());
                String sTime=timeFormat.format(lianshimodel.get开始接待时间());
                String sDateTime=sDate+" "+sTime;
                String nowDateTimeStr= simpleDateFormat.format(nowDateTime);

                int s= getDistanceTimes(sDateTime,nowDateTimeStr);
                newmodel.set停留时间( s);

                newmodel.set顾客来源("散客");//看车比
                newmodel.set到店目的("看车比价");
                newmodel.set接待类型("展厅");
                newmodel.set操作人(zhanghao);
                newmodel.set更新账号(zhanghao);
                顾客进店记录表Model newmodel2 = custEnterStoreRecordRepository.save(newmodel);

                lianshimodel.set进店编号(newmodel2.get进店编号());
                Date nn = new Date();
                lianshimodel.set结束接待时间(new Time(nn.getTime()));
                lianshimodel.set是否接待完成("是");
                java.sql.Timestamp tssss = new java.sql.Timestamp(System.currentTimeMillis());
                lianshimodel.set更新时间(tssss);
                lianshimodel.set更新账号(zhanghao);
                teampRecepRepository.save(lianshimodel);

            }

            flag = true;
        } catch (Exception e) {
            flag = false;
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("数据更新异常。", e);
        }
        return flag;
    }
    /**
     * 两个时间相差距离多少天多少小时多少分多少秒
     * @param str1 时间参数 1 格式：1990-01-01 12:00:00
     * @param str2 时间参数 2 格式：2009-01-01 12:00:00
     * @return long[] 返回值为：{天, 时, 分, 秒}
     */
    public static int getDistanceTimes(String str1, String str2) {
        Date one;
        Date two;
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        int fen=0;
        try {
            one = simpleDateFormat.parse(str1);
            two = simpleDateFormat.parse(str2);
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff ;
            if(time1<time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
            day = diff / (24 * 60 * 60 * 1000);
            hour = (diff / (60 * 60 * 1000) - day * 24);
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
            sec = (diff/1000-day*24*60*60-hour*60*60-min*60);
            fen=(int)((hour*60)+ min+ day*24*60);
            if(one.after(two)){
                return -fen;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        // long[] times = {day, hour, min, sec};

        return fen;
    }
    @Override
    public boolean updTeampRecepForChangeSale(UpdTeampRecepForChangeSaleRequest request) {
        boolean flag;
        try {
            teampRecepRepository.updTeampRecepForChangeSale(request.销售顾问, request.接待类型, request.临时接待编号);
            flag = true;
        } catch (Exception e) {
            flag = false;
            logger.error("数据更新异常。", e);
        }
        return flag;
    }

    @Override
    public boolean cancelSalesConsultant(Integer teampReceptionNum) {
        boolean flag;
        try {
            teampRecepRepository.cancelSalesConsultant(teampReceptionNum);
            flag = true;
        } catch (Exception e) {
            flag = false;
            logger.error("数据取消异常。", e);
        }
        return flag;

    }

    @Override
    public ResultData updSalesConsultantStartDriveTime(Integer teampReceptionNum) {
        ResultData resultData = new ResultData();
        resultData.setResult("true");
        resultData.setMessage("正常");
        临时接待记录Model 临时接待记录Model = teampRecepRepository.findOne(teampReceptionNum);
        if (临时接待记录Model == null) {
            resultData.setResult("false");
            resultData.setMessage("找不到对应的临时接待记录");
            return resultData;
        }
        if (临时接待记录Model.get开始试驾时间() != null) {
            resultData.setResult("true");
            resultData.setMessage(String.format("销售顾问已录入开始试乘试驾时间：%s", 临时接待记录Model.get开始试驾时间()));
            return resultData;
        }
        try {
            Date date = new Date(System.currentTimeMillis());
            DateFormat dateFormat = new SimpleDateFormat("HH:mm:SS");
            String prase = dateFormat.format(date);
            Date finalDate = dateFormat.parse(prase);
            teampRecepRepository.updSalesConsultantStartDriveTime(finalDate, teampReceptionNum);
        } catch (Exception e) {
            resultData.setResult("false");
            resultData.setMessage("未知异常");
            logger.error("更新试乘试驾开始时间异常", e);
        }
        return resultData;
    }

    @Override
    public ResultData updSalesConsultantEndDriveTime(Integer teampReceptionNum) {
        ResultData resultData = new ResultData();
        resultData.setResult("true");
        resultData.setMessage("正常");
        临时接待记录Model 临时接待记录Model = teampRecepRepository.findOne(teampReceptionNum);
        if (临时接待记录Model == null) {
            resultData.setResult("false");
            resultData.setMessage("找不到对应的临时接待记录");
            return resultData;
        }
        if (临时接待记录Model.get结束试驾时间() != null) {
            resultData.setResult("true");
            resultData.setMessage(String.format("销售顾问已录入结束试乘试驾时间：%s", 临时接待记录Model.get结束试驾时间()));
            return resultData;
        }
        try {
            Date date = new Date(System.currentTimeMillis());
            DateFormat dateFormat = new SimpleDateFormat("HH:mm:SS");
            String prase = dateFormat.format(date);
            Date finalDate = dateFormat.parse(prase);
            teampRecepRepository.updSalesConsultantEndDriveTime(finalDate, teampReceptionNum);
        } catch (Exception e) {
            resultData.setResult("false");
            resultData.setMessage("未知异常");
            logger.error("更新试乘试驾结束时间异常", e);
        }
        return resultData;
    }

    @Override
    public ResultData testDriveProcess(Integer flag, Integer tempReceptionNum) {
        ResultData resultData = new ResultData();
        if (tempReceptionNum == null) {
            resultData.setResult("false");
            resultData.setMessage("临时接待编号为空");
            return resultData;
        }
        临时接待记录Model 临时接待记录Model = teampRecepRepository.findOne(tempReceptionNum);
        if (临时接待记录Model == null) {
            resultData.setResult("false");
            resultData.setMessage("找不到对应的临时接待记录");
            return resultData;
        }
        // check开始试驾时间
        if (flag == 1) {
            if (临时接待记录Model.get开始试驾时间() != null) {
                resultData.setResult("true");
                resultData.setMessage(临时接待记录Model.get开始试驾时间().toString());
            } else {
                resultData.setResult("false");
                resultData.setMessage("时间为空");
            }
            // check结束试驾时间
        } else if (flag == 2) {
            if (临时接待记录Model.get开始试驾时间() != null) {
                resultData.setResult("true");
                resultData.setMessage(临时接待记录Model.get结束试驾时间().toString());
            } else {
                resultData.setResult("false");
                resultData.setMessage("时间为空");
            }
        }
        return resultData;
    }

    @Override
    public boolean updSalesConsultantEndDriveTimeByDate(UpdSalesConsultantEndDriveTimeByDateRequest request) {
        boolean flag;
        try {
            Date date = new Date(System.currentTimeMillis());
            DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
            DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
            String prase = dateFormat.format(date);
            Date finalDate = dateFormat.parse(prase);
            //接待日期 yyyy:MM:dd
            String jdPrase = dateFormat2.format(request.日期);
            Date jdDate = dateFormat2.parse(jdPrase);
            teampRecepRepository.updSalesConsultantEndDriveTimeByDate(finalDate, request.许可, request.销售顾问, jdDate);
            flag = true;
        } catch (Exception e) {
            flag = false;

            logger.error("数据更新异常。", e);
        }
        return flag;
    }

    @Override
    public List getCurrentDaySalePerson(String permit, Date date) {
        return foreGroundRepository.getCurrentDaySalePerson(permit, date);
    }

    @Override
    public List getCurrentDaySaleWork(String permit, Date date) {
        return foreGroundRepository.getCurrentDaySaleWork(permit, date);
    }

    @Override
    public List getSaleUnDoneService(String permit, Date date) {
        return foreGroundRepository.getSaleUnDoneService(permit, date);
    }

    @Override
    public List getSalePicPath(String permit) {
        return foreGroundRepository.getSalePicPath(permit);
    }

    @Override
    public boolean saveSaleTempRecord(临时接待记录Model old) {
        try {
            临时接待记录Model newmodel = new 临时接待记录Model();
            newmodel.set许可(old.get许可());
            newmodel.set销售顾问(old.get销售顾问());
            newmodel.set接待类型(old.get接待类型());
            newmodel.set是否接待完成(old.get是否接待完成());
            newmodel.set更新账号(old.get更新账号());
            newmodel.set进店类型(old.get进店类型());

            java.sql.Time newmodeltime = new java.sql.Time(System.currentTimeMillis());
            newmodel.set开始接待时间(newmodeltime);
            java.sql.Date newmodeltime2 = new java.sql.Date(System.currentTimeMillis());
            newmodel.set接待日期(newmodeltime2);

            teampRecepRepository.save(newmodel);
        } catch (Exception e) {
            logger.error("数据新增异常。", e);
        }
        return true;
    }

    @Override
    public Map saveSaleTempRecordBySC(String Dealer, String User, String startTime) {
        Map re = new HashMap();
        try {
            临时接待记录Model newmodel = new 临时接待记录Model();
            newmodel.set许可(Dealer);
            newmodel.set销售顾问(User);
            newmodel.set接待类型("1");
            newmodel.set是否接待完成("否");
            newmodel.set更新账号(User);
            newmodel.set进店类型("到店");

            // 最早開啓時間
            String minTimeStr = "17:30:00";
            Time minTime = DateFormatUtils.parseStrToSqlTime(minTimeStr);
            // 當前系統時間
            String nowStr = DateFormatUtils.getFormatDateToString(new Date(),"HH:mm:ss");
            Time nowTime = DateFormatUtils.parseStrToSqlTime(nowStr);
            // 前臺錄入時間
            Time inputTime = DateFormatUtils.parseStrToSqlTime(startTime);

            // 系統時間晚於最小時間 且 錄入時間小於最小時間
            if (inputTime!=null
                    && nowTime.getTime()>minTime.getTime()
                    && inputTime.getTime()>minTime.getTime()
                    && nowTime.getTime()>inputTime.getTime()){
                newmodel.set开始接待时间(inputTime);
                newmodel.set接待日期(new java.sql.Date(System.currentTimeMillis()));
                newmodel = teampRecepRepository.save(newmodel);

                re.put("custEnterID",newmodel.get临时接待编号());
                re.put("custEnterDate",newmodel.get接待日期().toString());
                re.put("custEnterTime",newmodel.get开始接待时间().toString());
                re.put("receptionState","接待中");
                re.put("custInroomType","到店");
                re.put("message","开始成功！");
                re.put("result","00");

                logger.info("非工作时间进店:Dealer={},User={},startTime={}",Dealer,User,startTime);
            } else if (inputTime!=null
                    && inputTime.getTime()>nowTime.getTime()){
                re.put("message","录入时间晚于当前时间"+nowStr+",无法开始接待");
                re.put("result","02");
            } else {
                re.put("message","当前时间早于"+minTimeStr+",无法开始接待");
                re.put("result","02");
            }
        } catch (Exception e) {
            logger.error("saveSaleTempRecordBySC出錯:Dealer={},User={},Time={}",Dealer,User,startTime, e);
            re.put("message","开始接待出错!");
            re.put("result","01");
        }
        return re;
    }

    @Override
    @Transactional
    public boolean updateSalePersonStatus(销售顾问状态Model saleStatusModel) {
        try {
            //先判断是否有数据
            销售顾问状态ModelPK pk = new 销售顾问状态ModelPK();
            pk.set日期(saleStatusModel.get日期());
            pk.set许可(saleStatusModel.get许可());

            pk.set销售顾问(saleStatusModel.get销售顾问());
            销售顾问状态Model old = saleStatusRepository.findOne(pk);
            if (old != null && !old.equals("")) {
                if (!"".equals(saleStatusModel.get状态码()) && saleStatusModel.get状态码() != null) {
                    old.set状态码(saleStatusModel.get状态码());
                }
                if (!"".equals(saleStatusModel.get排班顺序()) && saleStatusModel.get排班顺序() != null) {
                    old.set排班顺序(saleStatusModel.get排班顺序());
                }
                if (!"".equals(saleStatusModel.get是否当班()) && saleStatusModel.get是否当班() != null) {
                    old.set是否当班(saleStatusModel.get是否当班());
                }

                saleStatusRepository.save(old);
            } else {
                //新增
                销售顾问状态Model newmodel = new 销售顾问状态Model();
                newmodel.set状态码(saleStatusModel.get状态码());
                newmodel.set排班顺序(saleStatusModel.get排班顺序());
                newmodel.set是否当班(saleStatusModel.get是否当班());
                newmodel.set许可(saleStatusModel.get许可());
                newmodel.set日期(saleStatusModel.get日期());
                newmodel.set销售顾问(saleStatusModel.get销售顾问());
                saleStatusRepository.save(newmodel);
            }
        } catch (Exception e) {
            logger.error("数据更新异常。", e);

            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        return true;
    }

    @Override
    @Transactional
    public int updateSalePersonStatus(List<销售顾问状态Model> saleStatusList) {
        int success = 0;
        for (销售顾问状态Model saleStatusModel : saleStatusList) {
            try {
                saleStatusRepository.deleteSaleStatusByPermitAndDate(saleStatusModel.get许可(), saleStatusModel.get日期());
                saleStatusRepository.save(saleStatusModel);

                success++;
            } catch (Exception e) {
                logger.error("数据更新异常。", e);
            }
        }
        return success;
    }

    @Override
    public String getSaleStatusCode(销售顾问状态Model saleStatusMode) {
        return foreGroundRepository.getSaleStatusCode(saleStatusMode);
    }

    public boolean updateSCStatus(String permit, List<ForeGroundService.GetUpdateSCStatus> list) {
        boolean flag = false;
        try {
            if (list != null && !list.isEmpty()) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                for (GetUpdateSCStatus getUpdateSCStatus : list) {
                    //先判断是否有数据
                    销售顾问状态ModelPK pk = new 销售顾问状态ModelPK();
                    if (getUpdateSCStatus.日期 == null || "".equals(getUpdateSCStatus.日期)) {
                        return flag;
                    }
                    pk.set日期(new java.sql.Date(sdf.parse(getUpdateSCStatus.日期).getTime()));
                    pk.set许可(permit);

                    pk.set销售顾问(getUpdateSCStatus.销售顾问);
                    销售顾问状态Model old = saleStatusRepository.findOne(pk);
                    if (old != null && !old.equals("")) {
                        if (!"".equals(getUpdateSCStatus.状态码) && getUpdateSCStatus.状态码 != null) {
                            old.set状态码(getUpdateSCStatus.状态码);
                        }
                        if (!"".equals(getUpdateSCStatus.排班顺序) && getUpdateSCStatus.排班顺序 != null) {
                            old.set排班顺序(Integer.parseInt(getUpdateSCStatus.排班顺序));
                        }
                        if (!"".equals(getUpdateSCStatus.是否当班) && getUpdateSCStatus.是否当班 != null) {
                            old.set是否当班(getUpdateSCStatus.是否当班);
                        }

                        saleStatusRepository.save(old);
                    } else {
                        //新增
                        销售顾问状态Model newmodel = new 销售顾问状态Model();
                        newmodel.set状态码(getUpdateSCStatus.状态码);
                        newmodel.set排班顺序(Integer.parseInt(getUpdateSCStatus.排班顺序));
                        newmodel.set是否当班(getUpdateSCStatus.是否当班);
                        newmodel.set许可(permit);
                        newmodel.set日期(new java.sql.Date(sdf.parse(getUpdateSCStatus.日期).getTime()));
                        newmodel.set销售顾问(getUpdateSCStatus.销售顾问);
                        saleStatusRepository.save(newmodel);
                    }
                }
                flag = true;
            }
        } catch (Exception e) {
            logger.error("更新销售顾问状态的销售顾问异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        if (!flag) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return flag;
    }

}
